$('#header').load('head.html')


$(window).scroll(function () {
  if ($(window).scrollTop() > 80) {
    $('.main-right').css("position", "fixed");
    if ($(window).scrollTop() > 10000) {
      $('.main-right').css("position", "");
    }
  } else {
    $('.main-right').css("position", "");

  }
});


$('.main-left span').hover(function () {
  $(this).parent().siblings('b').stop().animate({
    right: "-15px",
    color: "yellow"
  }, 500)

}, function () {
  $(this).parent().siblings('b').stop().animate({
    right: "-10px",
    color: "red"
  }, 500)
})

// -----------加入购物车-----------
$('.main-right input').eq(0).hover(function () {
  $(this).css("background", "white")
  $(this).css("color", "black")
  $(this).css("border", "1px solid #cacaca")
}, function () {
  $(this).css("background", "black")
  $(this).css("color", "white")
  $(this).css("border", "0")
})
// -----------------放大镜-------------
$(function () {
  fn(1)
  fn(0)
  fn(2)
  fn(3)
  fn(4)
  function fn(n) {
    var shadeWidth = $('.shade').eq(n).width(),//阴影的宽度 
      shadeHeight = $('.shade').eq(n).height(),//阴影的高度 
      middleWidth = $('.container').eq(n).width(),//容器的宽度 
      middleHeight = $('.container').eq(n).height(),//容器的高度 
      bigImgWidth = $('.shade img').eq(n).width(),//放大图片盒子的宽度 
      bigImgHeight = $('.shade img').eq(n).height(),//放大图片盒子的高度 
      rateX = bigImgWidth / middleWidth,//放大区和遮罩层的宽度比例2 
      rateY = bigImgHeight / middleHeight;//放大区和遮罩层的高度比例2 
    //当鼠标移入与移出时阴影与放大去显现/消失 
    $('.container').eq(n).hover(function () {
      $('.shade').eq(n).show();
      $('.big').eq(n).show();
    }, function () {
      $('.shade').eq(n).hide();
      $('.big').eq(n).hide();
    }).mousemove(function (e) {//当鼠标移动时，阴影和放大区图片进行移动 


      //记录下光标距离页面的距离 
      var x = e.pageX,
        y = e.pageY;

      //设置遮罩层的位置 
      $('.shade').eq(n).offset({
        top: y - shadeHeight / 2,
        left: x - shadeWidth / 2
      });

      //获取遮罩层相对父元素的位置 
      var cur = $('.shade').eq(n).position(),
        _top = cur.top,
        _left = cur.left,
        hdiffer = middleHeight - shadeHeight,
        wdiffer = middleWidth - shadeWidth;

      if (_top < 0) _top = 0;
      else if (_top > hdiffer) _top = hdiffer;
      if (_left < 0) _left = 0;
      else if (_left > wdiffer) _left = wdiffer;

      //判断完成后设置遮罩层的范围 
      $('.shade').eq(n).css({
        top: _top,
        left: _left
      });


      //设置放大区图片移动 
      $('.shade img').eq(n).css({
        top: - _top * rateY * 2 / 2,
        left: - _left * rateX * 2 / 2
      });

    });;

  }
});

// -------------------详情图片链接-----------
let oPic = document.querySelector('.onepic')
let oTwoPic = document.querySelector('.one')
pAjax({
  url: '../server/detail.php',
  data: {
    id: localStorage.getItem('detailId') - 0 //queryString('id') - 0 
  }
}).then(function (res) {
  let json = JSON.parse(res)

  oPic.innerHTML = ` <img src="${json.goods_bigPic1}" style="display: block;width: 590px;height: 779px;">  `
})

pAjax({
  url: '../server/detail.php',
  data: {
    id: localStorage.getItem('detailId') - 0 //queryString('id') - 0 
  }
}).then(function (res) {
  let json = JSON.parse(res)

  oTwoPic.innerHTML = ` <img src="${json.goods_bigPic1}" style="display: block;width: 1180px;height: 1558px;"> `
})
// ---------------详情图片渲染-----------
// 渲染数据
let arrImg = [
  {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c445e3af.jpg',
    video: 'https://assets.sisley.com.cn/upload/%E8%A7%86%E9%A2%91/Sisleya_1m_Asia_chinese24m.mp4',
    videoFlag: true

  },
  {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c4ae383e.jpg',
    videoFlag: false
  },
  {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c5046d8c.jpg',
    videoFlag: false
  },
  {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c54d6d4a.jpg',
    videoFlag: false
  },
  {

    img: ' https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c5a0de48.jpg',
    videoFlag: false
  },
  {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c5f9637f.jpg',
    videoFlag: false
  }, {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3fc4877ef74.jpg',
    videoFlag: false
  }, {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c7e40d6c.jpg',
    videoFlag: false
  }, {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f3f7c8404729.jpg',
    videoFlag: false
  }, {
    img: 'https://assets.sisley.com.cn//cms/upload/spu_images/255/5f44de4406029.jpg',
    videoFlag: false
  }
]

$.each(arrImg, function (index, ele) {
  $('.image-details').append(`
  <img _src="${ele.img}" alt="">
      <div class="video-details ${ele.videoFlag ? 'show' : ''} ">
        <video controls>
          <source src="${ele.video}">
        </video>
      </div>
  `)
})
var aImg = document.querySelectorAll('.image-details img')

// var top = document.documentElement.scrollTop
var clientH = document.documentElement.clientHeight

console.log(clientH)

aImg.forEach((ele) => {
  if (clientH >= ele.offsetTop) {
    ele.src = ele.getAttribute('_src')
  }
})

window.onscroll = function () {
  var top = document.documentElement.scrollTop
  var clientH = document.documentElement.clientHeight

  aImg.forEach((ele) => {
    if (top + clientH >= ele.offsetTop) {
      ele.src = ele.getAttribute('_src')
    }
  })
}

// ------------列表详情跳转---------
function queryString(attr) {
  let n = window.location.href.indexOf('?')
  let arr = window.location.href.slice(n + 1).split('&')
  let obj = {}

  arr.forEach(function (ele, index) {
    obj[ele.split('=')[0]] = ele.split('=')[1]
  })
  console.log(obj)
  return obj[attr]
}

// console.log()
// --------------------右边商品信息渲染-----------
let price = 0
let idNum = 0
let oMainRightDetail = document.querySelector('.main-right-detail')
pAjax({
  url: '../server/detail.php',
  data: {
    id: localStorage.getItem('detailId') - 0 //queryString('id') - 0 
  }
}).then(function (res) {
  let json = JSON.parse(res)
  console.log(json)
  price = json.goods_price
  idNum = json.goods_id
  oMainRightDetail.innerHTML = ` <span >${json.goods_name}</span>
  <p>${json.goods_engName}</p>
  <p>${json.goods_able}</p>
  <p>容量: <span>${json.goods_contain}</span> </p>`
})

let oMainRightPrice = document.querySelector('.main-right-price')
pAjax({
  url: '../server/detail.php',
  data: {
    id: localStorage.getItem('detailId') - 0 //queryString('id') - 0 
  }
}).then(function (res) {
  let json = JSON.parse(res)
  console.log(json)

  oMainRightPrice.innerHTML = `<span class="price" comm-id="${json.goods_id}">￥<strong>${price}</strong></span> `
})
// -----------------数量加------------
let a = 1
$('.add').click(function () {
  a++
  if (a >= 6) {
    a = 6
  }
  $('var').text(a)
  $('strong').text((price * a).toFixed(2))
  sessionStorage.setItem("number", a)
})
$('.reduce').click(function () {
  a--
  if (a <= 1) {
    a = 1
  }
  $('var').text(a)
  $('strong').text((price * a).toFixed(2))
  sessionStorage.setItem("number", a)
})

$('input').eq(0).click(function () {
  $('#all').css("display", "block")
  //  let shopMore = localStorage.getItem('shopArr')
  //  let localNumber= localStorage.getItem('number',shopMore.count)
  // if(localNumber == 6){
  //   $('.tips').css("display","block")
  // }else{
  $('.tips p span').text("成功加入购物车")
  $('.tips').css("display", "block")
  // }
})
$('.tips').click(function(){
  $(this).css("display","none")
  $('#all').css("display","none")
})

$('.tips p .no').click(function () {
  $('#all').css("display", "none")
  $('.tips').css("display", "none")
})

$('input').eq(1).click(function () {
  window.location.href = 'shopcar.html'
})
let arr = []
let oMainRight = document.querySelector('.main-right')
oMainRight.addEventListener('click', function (ev) {

  if (ev.target.tagName === 'INPUT') {
    let n = ev.target.previousElementSibling.children[0].getAttribute('comm-id')
    // let pic = ev.target.parentNode.previousElementSibling.children[2]
    // console.log(pic)
    let localPrice = ev.target.previousElementSibling.children[0].children[0].innerHTML
    let localTitle = ev.target.previousElementSibling.previousElementSibling.previousElementSibling.children[0].innerHTML
    let localImg = ev.target.parentNode.previousElementSibling.children[0].nextElementSibling.nextElementSibling.children[0].children[1].children[0].children[0].children[0].children[0].src
    let localNumber = ev.target.parentNode.children[0].children[3].children[0].innerHTML
    
    let detailNumber = sessionStorage.getItem("number", a)
    
    let iNow1 = 0
    // 去重
    var shop1 = localStorage.getItem('shopArr')
    if (shop1) {
      var oldarr1 = JSON.parse(shop1)
      shopdj(oldarr1)
    } else {
      var oldarr1 = []
      shopdj(oldarr1)
    }
    function shopdj(arr1) {
      function findArr1(arr1, n) {
        for (let i = 0; i < arr1.length; i++) {
          // 有相同去++
          if (arr1[i].id == n) {
            iNow1 = i
            return true
          }
        }
        return false
      }

      let flag1 = findArr1(arr1, n)
      if (flag1) {
        arr1[iNow1].count++
      } else {
        arr1.unshift({
          id: n,
          pic: localImg,
          name:localTitle,
          price: localPrice - 0,
          count: detailNumber,
          number:localNumber,
          flag: true
        })
      }
      // 存到本地
      console.log(arr1)
      localStorage.setItem('shopArr', JSON.stringify(arr1))
    }
  }
  })

                            // 轮播图

var iNowstar = 0
function autoplay () {
    iNowstar++
    if (iNowstar ===13) {
        iNowstar = 0
    $('.all1').css({left: -iNowstar*400})
    }
    // $('.all1').css({left: -iNowstar*400})
    $('.all1').stop().animate({left: -iNowstar*400},1000)

    

    $('.allline').stop().animate({
        width: 100,
        height: 100
    })

    

    // 页码效果
    var oNow=document.querySelector('.now1')
    $('.now1').stop().animate({top: 40},500,function(){
        if(oNow.style.top==='40px'){
            $('.now1').html(iNowstar+1)
            $('.now1').finish().animate({top: -10},1,function(){
                if(oNow.style.top==='-10px'){
                    $('.now1').finish().animate({top: 10},500)
                }
            })
        }
    })
   
    

}
$('.next1').click(autoplay)
$('.prev1').click(function() {
    iNowstar--
    if (iNowstar === -1) {
        iNowstar = 12
      // $('.all1').stop().animate({left: -iNowstar*400},1)
      $('.all1').css({left: -iNowstar*400})

    }else{
    // $('.all1').css({left: -iNowstar*400})
    $('.all1').stop().animate({left: -iNowstar*400},1000)
    }
    

    // 页码效果
    var oNow=document.querySelector('.now1')

    $('.now1').stop().animate({top: 40},500,function(){
        if(oNow.style.top==='40px'){
            $('.now1').html(iNowstar+1)
            $('.now1').finish().animate({top: -10},1,function(){
                if(oNow.style.top==='-10px'){
                    $('.now1').finish().animate({top: 10},500)
                }
            })
        }
    })
   
    // console.log(oNow.style.top)
    
})

 /* ------------------返回顶部-------------- */
 $(".return").hide();
 $(function() {
   $(window).scroll(function() {
     if ($(window).scrollTop() > 50) {
       $(".return").fadeIn(200);
       $(".return").hover(function(){
         $(this).css("background","black")
         $(this).children().css("color","white")
       },function(){
        $(this).css("background","white")
        $(this).children().css("color","black")
       })
     } else {
       $(".return").fadeOut(200);
     }
   });
   $(".return").click(function() {
     $('body,html').animate({
       scrollTop: 0
     },
     500);
     return false;
   });
 });

// -----------------尾部----------------
$("#foot").load('foot.html')
